import Treetable from './treetable.esm'
import swal from 'sweetalert'
import toastr from 'toastr'

export function treeify (el, expanded) {
  return new Treetable(el, {
    clickableNodeNames: true,
    expandable: true,
    indent: 35,
    onInitialized () {
      Object.keys(expanded).forEach(n => {
        this.expandNode(n)
      })
    },
    onNodeCollapse () {
      delete expanded[this.id]
    },
    onNodeExpand () {
      expanded[this.id] = 1
    }
  })
}

export function paging (vm, resource, pn, cb) {
  vm.param.pn = typeof pn === 'number' ? pn : 1
  vm.loading = true
  resource.query(vm.param).then(response => {
    vm.page = response.data
    vm.loading = false
    cb && cb()
  })
}

export const del = function (vm, resource, id, items, index) {
  swal({
    type: 'warning',
    title: '您确定?',
    text: '删除的记录将不能恢复!',
    showCancelButton: true,
    cancelButtonText: '取消',
    confirmButtonText: '是的, 我要删除!',
    confirmButtonColor: '#DD6B55',
    showLoaderOnConfirm: true,
    closeOnConfirm: false
  }, confirmed => {
    if (confirmed) {
      vm.loading = true
      resource.delete(id).then(response => {
        vm.loading = false
        if (response.data.success) {
          swal('已删除!', '您指定的记录已被删除.', 'success')
          return items.splice(index, 1)
        }
        swal('删除失败!', response.data.msg, 'error')
      }, response => {
        swal('操作失败', response.data.msg, 'error')
        vm.loading = false
      }).catch(error => {
        swal('操作失败', error, 'error')
        vm.loading = false
      })
    }
  })
}

export const showResponse = function (response, success, fail) {
  if (response.data.success) {
    return swal({type: 'success', title: '操作成功', text: '您的操作已经执行成功!'}, () => {
      success && success()
    })
  }
  if (response.data.errors) {
    toastr.warning(Object.keys(response.data.errors).map(k => response.data.errors[k]).join('<br>'))
  }
  if (response.data.msg) {
    swal('操作失败', response.data.msg, 'error')
  }
  fail && fail()
}

export const closest = function (el, selector, ctx = document) {
  if (!el) return null
  while (el = el.parentNode) {
    if (el === ctx || matches(el, selector))
      return el
  }
}

export const matches = function (el, selector) {
  if (!el) return false
  selector = selector.split('.')
  var tag = selector.shift().toUpperCase(),
      re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g')
  return (
      (tag === '' || el.nodeName.toUpperCase() == tag) &&
      (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
  )
}

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
export const debounce = function (func, wait, immediate) {
  var timeout, args, context, timestamp, result

  var later = function () {
    var last = Date.now() - timestamp

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function () {
    context = this
    args = arguments
    timestamp = Date.now()
    var callnow = immediate && !timeout
    if (!timeout) timeout = setTimeout(later, wait)
    if (callnow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}